package com.mvvm.store.retrofitwithrxjava;



import com.alibaba.fastjson.JSON;
import com.mvvm.store.MyApplication;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import okio.BufferedSource;
import okio.Okio;
import retrofit2.Converter;

/**
 * <b>类名称：</b> FastJsonResponseBodyConverter <br/>
 * <b>类描述：</b> ResponseBody转换器<br/>
 *
 * @version 1.0.0 <br/>
 */
public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Type type;

    public FastJsonResponseBodyConverter(Type type) {
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        BufferedSource bufferedSource = Okio.buffer(value.source());
        String tempStr = bufferedSource.readUtf8();
        bufferedSource.close();
        if (MyApplication.getInstance().isShouldReplace()) {
            MyApplication.getInstance().setShouldReplace(false);
            return JSON.parseObject(tempStr.replace(":[]", ":{}"), type);
        } else {
           System.out.println("JSON"+tempStr.toString());
            return JSON.parseObject(tempStr, type);
        }
    }
}
